package com.taxshare.tools.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Auther: pc
 * @Date: 2018/10/22 09:58
 * @Description:
 */
@Slf4j
public class Sha256Util {

  /**
   * sha256_HMAC加密
   *
   * @param message 消息
   * @param secret 秘钥
   * @return 加密后字符串
   */
  public static String sha256_HMAC(String message, String secret) {
    String hash = null;
    try {
      Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
      SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
      sha256_HMAC.init(secret_key);
      byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
      hash = byteArrayToHexString(bytes);
    } catch (Exception e) {
      log.error("Error HmacSHA256 加密异常:", e.getMessage());
    }
    return hash;
  }

  /**
   * 验签
   *
   * @param message 明文
   * @param secret 验签
   * @param signed 密文
   */
  public static boolean verifySign(String message, String secret, String signed) {
    boolean flag = false;
    try {
      flag = sha256_HMAC(message, secret).equals(signed);
    } catch (Exception e) {
      log.error("Sha256Util verifySign 验签异常:", e);
    }
    return flag;
  }


  /**
   * 将加密后的字节数组转换成字符串
   *
   * @param b 字节数组
   * @return 字符串
   */
  private static String byteArrayToHexString(byte[] b) {
    StringBuilder hs = new StringBuilder();
    String stmp;
    for (int n = 0; b != null && n < b.length; n++) {
      stmp = Integer.toHexString(b[n] & 0XFF);
      if (stmp.length() == 1) {
        hs.append('0');
      }
      hs.append(stmp);
    }
    return hs.toString().toLowerCase();
  }

}